import * as languages from './languages.js'
import type { HighlightLanguage } from './languages.js'

type LanguagesMap = Record<string, HighlightLanguage>
let languagesMap: LanguagesMap

const getLanguagesMap = (): LanguagesMap => {
    if (!languagesMap) {
        languagesMap = Object.values(languages).reduce((result, item) => {
            item.aliases.forEach((alias: string): void => {
                result[alias] = item
            })
            return result
        }, {} as LanguagesMap)
    }

    return languagesMap
}

export const resolveLanguage = (info: string): HighlightLanguage => {
    const alias: string = info.match(/^([^ :[{]+)/)?.[1] || ''
    return (
        getLanguagesMap()[alias] ?? {
            name: alias,
            ext: alias,
            aliases: [alias]
        }
    )
}
